package com.wsx.boots.auth.config;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.management.RuntimeErrorException;
import java.util.List;
import java.util.Map;

/**
 * Created by wangshuaixin on 17/4/23.
 */
public class HmacSHA256Utils {

    public static final String UTF_CODE = "UTF-8";

    public static String digest(String key, String content) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            byte[] secretByte = key.getBytes(UTF_CODE);
            byte[] dataByte = content.getBytes(UTF_CODE);

            SecretKey secretKey = new SecretKeySpec(secretByte, "HMACSHA256");
            mac.init(secretKey);

            byte[] doFinal = mac.doFinal(dataByte);
            byte[] hex = new Hex().encode(doFinal);
            return new String(hex, UTF_CODE);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    public static String digest(String key, Map<String, ?> map) {
        StringBuilder builder = new StringBuilder();
        for (Object values : map.values()) {
            if (values instanceof String[]) {
                for (String value : (String[])values) {
                    builder.append(value);
                }
            } else if (values instanceof List) {
                for (String value : (List<String>)values) {
                    builder.append(value);
                }
            } else {
                builder.append(values);
            }
        }

        return digest(key, builder.toString());
    }
}
